package com.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pojo.MovieList;
import com.service.DyService;
import com.service.DyTypeService;
import com.service.SpecialFilmListService;
import com.service.SpecialService;
import com.util.DesUtil;
import com.util.HardUtil;
import com.util.MD5Util;
import com.util.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings("ALL")
@Component("TimeTaskAlreadyDownAddDBService")
public class TimeTaskAlreadyDownAddDBService {


    @Value("${server.port}")
    private String port;


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    @Qualifier("StringRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private DyTypeService dyTypeService;

    @Autowired
    private DyService dyService;

    @Value("${server.url}")
    private String server;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private SpecialService specialService;

    @Autowired
    private SpecialFilmListService specialFilmListService;

    @Autowired

    @Value("${dy.tmp}")
    private String tmp;

    @Value("${dy.home}")
    private String home;

    private String downImage(String img, boolean rename) {
        File baseImage = new File(home + "/images");
        if (baseImage.exists() == false) {
            baseImage.mkdir();
        }
        String dir = StringUtils.getDir(img);
        String filename = StringUtils.getFilename(img);

        File imageBaseFile = new File(baseImage + dir);
        if (imageBaseFile.exists()) {
            imageBaseFile.mkdirs();
        }


        String newfilename = IdUtil.fastSimpleUUID() + ".png";
        String url = server + img;
        if (img.startsWith("http://") == true) {
            url = img;
        }


        try {
            if (rename) {
                File downfilename = new File(baseImage, newfilename);
                HttpUtil.downloadFile(url, downfilename);
            } else {
                File downfilename = new File(imageBaseFile, filename);
                HttpUtil.downloadFile(url, downfilename);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return newfilename;
    }




    /**
     * 更新节目列表
     */
    @Scheduled(cron = "15 2/5 * * * ?")
    public synchronized void crossUpdateDy() {



        File dyFile = new File(home + "dy/");
        if (dyFile.exists() == false) {
            dyFile.mkdir();
        }

        //RLock rLock = redissonClient.getLock("crossUpdateDy");
        try {


            dyTypeService.xiajiaExpire();
            boolean enable = enableDown();
            if (enable) {
                updateDy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }


    public boolean enableDown() {
        int begin = 0;
        int end = 24;
        try {
            InputStream is = new FileInputStream("time.properties");
            Properties p = new Properties();
            p.load(is);
            String beginTime = p.getProperty("begin");
            String endTime = p.getProperty("end");
            begin = Integer.parseInt(beginTime);
            end = Integer.parseInt(endTime);
        } catch (Exception e) {
            // e.printStackTrace();
        }

        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if (hour < begin && hour > end) {
            return false;
        }
        return true;
    }


    private List<MovieList> removeAll(List<MovieList> src, List<MovieList> target) {
        LinkedList<MovieList> result = new LinkedList<MovieList>(src); //大集合用linkedlist
        HashSet<MovieList> targetHash = new HashSet<MovieList>(target); //小集合用hashset
        Iterator<MovieList> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            MovieList m = iter.next();
            if (targetHash.contains(m)) {
                iter.remove();
            }
        }
        return result;
    }










    /**
     * 更新电影
     */
    //@PostConstruct
    public void updateDy() {
        List<MovieList> remoteList = null;
        String mainboardID = HardUtil.getMainBorId();
        String url = server + "/api/v1/getMovieBySite?mainboardID={1}";
        if (server.startsWith("http://172.") || server.startsWith("http://192.") || server.startsWith("http://10.")){
           // url = server + "/api/v1/getAllDy?mainboardID={1}";
        }
        String response = restTemplate.getForObject(url, String.class, mainboardID);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject != null) {
            int code = jsonObject.getInteger("code");
            if (code != 200) {
                System.out.println(jsonObject.getString("msg"));
                return;
            }

            //获取远程节目列表
            remoteList = jsonObject.parseArray(jsonObject.getString("data"), MovieList.class);
            //获取本地节目列表
            List<MovieList> localList = dyService.list();


            //比较
            List<MovieList> addList = new ArrayList(); //要新增的电影
            List<MovieList> removeList = new ArrayList();//要删除的电影

            if (remoteList != null) {
                addList = removeAll(remoteList, localList);
            }
            if (localList != null && remoteList != null) {

                removeList = removeAll(localList, remoteList);
            }

           // System.out.println("要新增电影:"+addList.size());


            //更新下载
            if (addList != null) {
                for (MovieList m : addList) {
                    boolean f = enableDown();
                    if (f == false) {
                        return;
                    }

                    //拼接下载地址
                    String ip = m.getIp();

                    String dy_down_ip = (String)redisTemplate.boundValueOps("dy_down_ip").get();
                    String dy_down_port = (String)redisTemplate.boundValueOps("dy_down_port").get();
                    String dy_down_status = (String)redisTemplate.boundValueOps("dy_down_status").get();
                    if ("1".equals(dy_down_status) && StringUtils.isEmpty(dy_down_ip)==false){
                        ip = dy_down_ip;
                    }




                    if (ip == null || ip.trim().length() == 0) {
                        continue;
                    }
                    String downLoadUrl = ip;
                    if (ip.startsWith("http://") == false) {
                        downLoadUrl = "http://" + ip;
                    }
                    Integer port = m.getPort();
                    if (port == null) {
                        continue;
                    }
                    downLoadUrl = downLoadUrl + ":" + port;
                    //判断是否已下载
                    String path = m.getPath();
                    String name = m.getProgram_name();
                    String nameMd5 = MD5Util.getMD5(name);
                    if (path == null) {
                        path = "/";
                    }
                    if (path != null && path.startsWith("/res") == false) {
                        if (path.startsWith("/")) {
                            path = "/res" + path;
                        } else {
                            path = "/res/" + path;
                        }
                    }

                    String downPath = path;
                    if ("1".equals(dy_down_status) && StringUtils.isEmpty(dy_down_ip)==false){
                        downPath = m.getMd5();
                        if (downPath==null){
                            String extFile = ".mp4";
                            int index = path.lastIndexOf('.');
                            if (index > -1) {
                                extFile = path.substring(index);
                            }
                            downPath =nameMd5+"."+extFile;
                        }
                    }
                    if (downPath != null && downPath.startsWith("/home")) {
                        downPath = downPath.replaceFirst("/home", "");
                    } else if (downPath != null && downPath.startsWith("home")) {
                        downPath = downPath.replaceFirst("home", "");
                    } else if (downPath != null && downPath.startsWith("/res")) {
                        downPath = downPath.replaceFirst("/res", "");
                    } else if (downPath != null && downPath.startsWith("res")) {
                        downPath = downPath.replaceFirst("res", "");
                    }

                    if (downPath != null && downPath.startsWith("/res")) {
                        downPath = downPath.replaceFirst("/res", "");
                    }
                    if (downPath != null && downPath.startsWith("res")) {
                        downPath = downPath.replaceFirst("res", "");
                    }

                    if (downPath.startsWith("/dy") == false || downPath.startsWith("dy") == false) {
                        if (downPath.startsWith("/")) {
                            downPath = "/dy" + downPath;
                        } else {
                            downPath = "/dy/" + downPath;
                        }
                    }
                    if (downPath != null && downPath.startsWith("/") == false) {
                        downPath = downPath + "/";
                    }
                    if (downPath.startsWith("/") == false) {
                        downPath = "/" + downPath;
                    }
                    downLoadUrl = downLoadUrl + downPath;

                    String extFile = ".mp4";
                    int index = path.lastIndexOf('.');
                    if (index > -1) {
                        extFile = path.substring(index);
                    }
                    //-------------------------------------------------------------------
                    String key = MD5Util.getMD5("1234@#$.Ab" + new SimpleDateFormat("yyyyMMddHH").format(new Date()));
                    downLoadUrl = downLoadUrl + "?key=" + DesUtil.encryptThreeDESECB(mainboardID, key);

                    File dyFile = new File(home + "dy/", nameMd5 + extFile);
                    File tmpFile = new File(tmp + "/" + name + extFile);
                    boolean downok = true;
                    if (dyFile.exists() == false) //不存在就下载
                    {

                       continue;

                    }
                    //写本地数据库
                    MovieList localM = new MovieList();
                    BeanUtil.copyProperties(m, localM,"local_img","md5", "isdown");
                    if (downok)
                    {
                        localM.setIsdown(1);
                    }
                    else {
                        localM.setIsdown(0);
                    }
                    localM.setMd5(nameMd5 + extFile);

                    String localImg = localM.getLocal_img();
                    boolean needDown = false;
                    if (localImg != null) {
                        File file1 = new File(home + "images/", localImg);
                        if (file1.exists() == false) {
                            needDown = true;

                        }
                    } else {

                        needDown = true;
                    }

                    if (needDown) {
                        String resultImg = downImage(localM.getBig_poster(), true);
                        localM.setLocal_img(resultImg);
                    }


                    dyService.save(localM);

                }
            }


        }


    }





}
